package com.woniuxy.predicate;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {

    public AgeRoutePredicateFactory() {
        super(AgeRoutePredicateFactory.Config.class);
    }

    // 读取配置文件中的参数，并封装到Config内部类的对象中
    @Override
    public List<String> shortcutFieldOrder() {
        // 该集合中元素的顺序，必须与配置文件中参数的顺序一致
        return Arrays.asList("minAge", "maxAge");
    }

    //断言逻辑
    @Override
    public Predicate<ServerWebExchange> apply(AgeRoutePredicateFactory.Config config) {
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                // 1. 接收age请求参数
                String ageStr = serverWebExchange.getRequest().getQueryParams().getFirst("age");

                // 2. 如果不为空，则进行路由逻辑判断
                if (StringUtils.isBlank(ageStr)) {
                    return false;
                }
                try {
                    int age = Integer.parseInt(ageStr);
                    return age >= config.getMinAge() && age <= config.getMaxAge();
                } catch (NumberFormatException e) {
                    return false;
                }

            }
        };
    }


    // 该类用于封装配置文件中的对应参数
    public static class Config {
        private int minAge;
        private int maxAge;

        public int getMinAge() {
            return minAge;
        }

        public void setMinAge(int minAge) {
            this.minAge = minAge;
        }

        public int getMaxAge() {
            return maxAge;
        }

        public void setMaxAge(int maxAge) {
            this.maxAge = maxAge;
        }
    }
}
